package com.qf.day10;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DoubleCharReplacement {
    public static void main(String[] args) {
        String input1 = "hello nice to meet you";
        String output1 = replaceDoubleChars(input1);
        System.out.println(output1);

        String input2 = "浩浩荡荡";
        String output2 = replaceDoubleChars(input2);
        System.out.println(output2);
    }

    public static String replaceDoubleChars(String input) {
        // 匹配任意字符重复两次的正则表达式
        Pattern pattern = Pattern.compile("(.)\\1");
        Matcher matcher = pattern.matcher(input);

        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            // 替换找到的叠字为单个字符加上波浪号
            matcher.appendReplacement(sb, matcher.group(1) + "~");
        }

        matcher.appendTail(sb);

        return sb.toString();
    }
}
